package org.groovyflow.spring.web;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

public class StandardSuffixDynamicFinder extends AbstractDynamicFinder {

	private String suffix;
	private String seperator;
	
	@Override
	protected List findObjectAndMethod(HttpServletRequest request,
			HttpServletResponse response, ClassLoader classLoader) {
		String ctrlString = findControlString(request);
		ctrlString = StringUtils.replace(ctrlString, suffix, "");
		if(ctrlString.startsWith("/"))
			ctrlString = ctrlString.substring(1);
		StringTokenizer tk = new StringTokenizer(ctrlString, this.seperator);
		
		//TODO  Identical to PrettyURLDynamicFinder from here on.  Need to refactor.
		List tokens = new ArrayList();
		
		while(tk.hasMoreTokens()){
			tokens.add(tk.nextToken());
		}
		if(tokens.isEmpty())
			throw new RuntimeException("Can't find class/method(or block) for " + ctrlString);
		String className = putClassNameTogether((String) tokens.get(0));
		Class clazz  = findClass(className, classLoader);
		Object theController = instantiate(clazz);
		//TODO  ??Make some allowance for the second element of the String being 
		//all digits, in which case we'll treat it as an id??  I've always thought that idea is stupid.
		String methName = tokens.size() == 1 ? request.getMethod().toLowerCase() : (String) tokens.get(1);
		Method method = findMethod(clazz, methName);
		
		List objAndMeth = new ArrayList();
		objAndMeth.add(theController);
		objAndMeth.add(method);
		
		return objAndMeth;
	}

	@Override
	public boolean isPrettyURLScheme() {
		return false;
	}

	public void setSuffix(String suffix) {
		this.suffix = suffix;
	}
	
	public void setSeperator(String seperator) {
		this.seperator = seperator;
	}	
	

}
